<!-- src/views/LifeCountdownDashboard.vue -->
<template>
  <div class="dashboard" style="padding: 20px; max-width: 1400px; margin: 0 auto; font-family: 'Helvetica Neue', Arial, sans-serif;">
    <h1 style="color: #333; text-align: center; margin-bottom: 30px;">📊 人生倒计时 - 用户数据看板</h1>

    <!-- 统计摘要卡片 -->
    <el-row :gutter="20" style="margin-bottom: 30px;">
      <el-col :span="6" v-for="(card, index) in summaryCards" :key="index">
        <el-card shadow="hover" :style="{ textAlign: 'center', backgroundColor: card.bgColor, color: '#fff' }">
          <h3 style="margin: 10px 0;">{{ card.value }}</h3>
          <p style="margin: 0; opacity: 0.9;">{{ card.label }}</p>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <!-- 年龄分布 -->
      <el-col :span="12">
        <div ref="ageChartRef" style="width: 100%; height: 100%; background: #fff; padding: 10px; border-radius: 8px;"></div>
      </el-col>

      <!-- 倒计时类型 -->
      <el-col :span="12">
        <div ref="typeChartRef" style="width: 100%; height: 600px; background: #fff; padding: 10px; border-radius: 8px;"></div>
      </el-col>
    </el-row>


    <!-- 底部说明 -->
    <div style="text-align: center; margin-top: 40px; color: #999; font-size: 14px;">
      <p>数据更新时间：{{ new Date().toLocaleString() }}</p>
      <p>本看板用于分析用户行为与情感唤醒效果，助力产品优化与人文关怀设计。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import 'element-plus/dist/index.css';
import { statistic ,agestats, timeRecord} from "@/api/wx/statistic"
import { get } from '@vueuse/core';

// 模拟统计数据
const summaryCards = ref([
  { label: '总用户数', value: '-', bgColor: '#409eff' },
  { label: '重要人生节点创建数', value: '-', bgColor: '#67c23a' },
  { label: '时间账本创建数', value: '-', bgColor: '#f56c6c' },
  { label: '每日一句收录数量', value: '-', bgColor: '#909399' },
]);

// 图表引用
const ageChartRef = ref(null);
const typeChartRef = ref(null);
const ages = ref([]);// 获取年龄段
const counts = ref([]); // 获取对应人数
const chartData = ref(null);

// 随机取一个颜色，保证颜色不重复
const usedColors = new Set();

function generateUniqueColor() {
  let color;
  do {
    color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
  } while (usedColors.has(color));
  
  usedColors.add(color);
  return color;
}

// Reset used colors when needed (e.g., when regenerating chart)
function resetUsedColors() {
  usedColors.clear();
}



function getStatistic(){
  statistic().then(response => {
    const data = response.data;
    summaryCards.value = [
      { label: '总用户数', value: data.userCount, bgColor: '#409eff' },
      { label: '重要人生节点创建数', value: data.lifeEventCount, bgColor: '#67c23a' },
      { label: '时间账本创建数', value: data.timeBookCount, bgColor: '#f56c6c' },
      { label: '每日一句收录数量', value: data.dailySentenceCount, bgColor: '#909399' },
    ];
  }).catch(error => {
    console.error("Failed to fetch statistics:", error);
  });
}

function getTimeRecord(){
  timeRecord().then(response => {
    const data = response.data;
    resetUsedColors();
    chartData.value = Object.entries(data).map(([name, value]) => ({
      name: name,
      value: value,
      itemStyle: { color: generateUniqueColor() }
    }));
    console.log(chartData.value);
    renderTypeChart();
    console.log(response.data);
  }).catch(error => {
    console.error("Failed to fetch time record:", error);
  });
}

function getAgeStats(){
  agestats().then(response => {
    console.log(response.data);
    const data = response.data;
    ages.value = Object.keys(data);
    counts.value = Object.values(data);
    renderAgeChart();
  }).catch(error => {
    console.error("Failed to fetch age statistics:", error);
  });
}

// 渲染图表函数
const renderAgeChart = () => {
  const chart = echarts.init(ageChartRef.value);
  const option = {
    title: { text: '用户年龄分布', left: 'center', textStyle: { fontSize: 16 } },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: ages.value },
    yAxis: { type: 'value', name: '人数', minInterval: 1 },
    series: [{
      data: counts.value,
      type: 'bar',
      itemStyle: { color: '#5470c6' },
      label: { show: true, position: 'top' }
    }]
  };
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
};

const renderTypeChart = () => {
  const chart = echarts.init(typeChartRef.value);
  const option = {
    title: { text: '时间账本类型分布', left: 'center', textStyle: { fontSize: 16 } },
    tooltip: { formatter: '{b}: {c} ({d}%)' },
    legend: { bottom: 'bottom', type: 'scroll' },
    series: [{
      type: 'pie',
      radius: '60%',
      data: chartData.value,
      label: { show: true }
    }]
  };
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
};




// 页面加载后渲染所有图表
onMounted(() => {
  getStatistic();
  getAgeStats();
  getTimeRecord();
});



</script>

<style scoped>
.dashboard {
  background-color: #f5f7fa;
  min-height: 100vh;
}
h1 {
  font-weight: 500;
}
</style>